/***
  Copyright (c) 2008-2012 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain	a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS,	WITHOUT	WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.
	
  From _The Busy Coder's Guide to Android Development_
    http://commonsware.com/Android
*/

package org.crosswalkproject.xwalkembed;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.display.DisplayManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.PowerManager.WakeLock;
import android.os.RemoteException;
import android.util.Log;
import android.view.Display;


import java.io.IOException;

import org.apache.http.message.BasicNameValuePair;
import org.crosswalkproject.bluetooth.bluetooth_sheep;
import org.crosswalkproject.iflytek.voicedemo.IatDemo;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ServerHandshake;

public class CallService extends Service {
  public static final String EXTRA_PLAYLIST="EXTRA_PLAYLIST";
  public static final String EXTRA_SHUFFLE="EXTRA_SHUFFLE";
public static final int TEST = 0;
  private boolean isPlaying=false;
 String playlist;
 private boolean useShuffle;
private BufferedReader Cin;
private PrintWriter Cout;
private Socket Csocket;
protected Timer mTimer;
protected Messenger cMessenger;
protected String str1;
private String ser_url="";
private int ser_port;   
private ExampleClient c = null;
private int have_str=0;/*1:receive str and then send out;2:receive new url and then connect 3:connect close or error need reconnect
4:html load fininsh */
private String loginCMD;
public int onLine_n;
private String ClienID0="setting:myID:d;recent call:a;";
public int wait_load;
public int onpause=0;//1: main activity is onpause
public String answser1;
private bluetooth_sheep bluetooth_s;
private int BT_status=0;/*0:ilde,1:scaning;2:connected*/
private WifiManager wifiManager; 

//public FT311UARTInterface uartInterfaceC;	
 @Override   
 public void onCreate() {   
     System.out.println("----> 锟斤拷锟斤拷锟斤拷锟斤拷"); 
     
     // uartInterfaceC = new FT311UARTInterface(this, null);
    //  uartInterfaceC.ResumeAccessory();
     update_loginID();
     new Thread(new ThreadShow()).start();  
     mTimer = new Timer();  
  //   start_boardcast(this);
  ///////////////////
     IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
     filter.addAction(Intent.ACTION_SCREEN_OFF);
     BroadcastReceiver mReceiver = new ScreenReceiver();
     registerReceiver(mReceiver, filter);
  ///////////////////////   
     bluetooth_s=new  bluetooth_sheep(this,null);
    
    // 
     
     
     
     super.onCreate(); 
     //
 }  
 
//wifi锟饺点开锟斤拷  
 public boolean setWifiApEnabled(boolean enabled) {  
	 wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);  
     if (enabled) { // disable WiFi in any case  
         //wifi锟斤拷锟饺点不锟斤拷同时锟津开ｏ拷锟斤拷锟皆达拷锟饺碉拷锟绞憋拷锟斤拷锟揭拷乇锟絯ifi  
         wifiManager.setWifiEnabled(false);  
     }  
     try {   
         //锟饺碉拷锟斤拷锟斤拷锟斤拷锟�  
         WifiConfiguration apConfig = new WifiConfiguration();  
         //锟斤拷锟斤拷锟饺碉拷锟斤拷锟斤拷锟�(锟斤拷锟斤拷锟斤拷锟斤拷锟街猴拷锟斤拷拥锟斤拷锟斤拷锟斤拷什么锟斤拷)  
         apConfig.SSID = "rsheep";  
         //锟斤拷锟斤拷锟饺碉拷锟斤拷锟斤拷锟�  
         apConfig.preSharedKey="123456789";  
             //通锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷鹊锟�  
         Method method = wifiManager.getClass().getMethod(  
                 "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);  
         //锟斤拷锟斤拷锟饺碉拷锟阶刺�  
         return (Boolean) method.invoke(wifiManager, apConfig, enabled);  
     } catch (Exception e) {  
         return false;  
     }  
 }  
 
 @Override  
 public void onDestroy() {  
     stopForeground(true);  
     Intent intent = new Intent("org.crosswalkproject.xwalkembed.destroy");  
     sendBroadcast(intent);  
     bluetooth_s.mBLE.close();
     super.onDestroy();  
 }  
 
//wifi锟饺点开锟斤拷  
 
 public void update_loginID()
 {
	 
	 SharedPreferences settings1 = getSharedPreferences("setting_infos", 0);  
     ClienID0 = settings1.getString("ID","");  
     ser_url=settings1.getString("URL","");  
     if(ser_url.length()<=0)
    	 ser_url="112.74.114.167:5000";
     if(ClienID0.length()<=12)
    	 ClienID0="setting:myID:d;recent call:a;";

     int ii= ClienID0.indexOf("myID:");
     if(ii>=0)
     {
     		ClienID0=ClienID0.substring(ii);
     		int jj= ClienID0.indexOf(";");
		if(jj<0)
			ClienID0=ClienID0.substring(5);
		else
			ClienID0=ClienID0.substring(5,jj);
     }
	 
     loginCMD=ClienID0+";login";
     have_str=2;	 
	 
 }

 private Handler mHandler = new Handler(){  
	   

		@Override  
	    public void handleMessage(Message msg) {  
	        super.handleMessage(msg);  
	        str1 = msg.getData().getString("text1"); 
		 int ii;
	        switch (msg.what) {  
	        case 0:  
	           // Log.e(TAG, "Get Message from MainActivity.");  
	            cMessenger = msg.replyTo;  
	            
	            
	           	Log.w(getClass().getName(), "send net:"+str1);
	           ii= str1.indexOf("uart:");
	            if(ii==0)
	            {
	            	 
	              // 	uartInterfaceC.SetConfig(Integer.parseInt(str1.substring(5)), (byte)8, (byte)1, (byte)0, (byte)0);	
	               
	            	return;
	            }
	           	ii= str1.indexOf("data");
	            if(ii==0)
	            {	str1=str1.substring(4);
	             //	uartInterfaceC.SendData(str1.length(), str1.getBytes());
	            	 
	            	return;
	            }
	           	ii= str1.indexOf("http://");
	            if(ii==0)
	            {
	              	Log.w(getClass().getName(), "  ii ");
	            	
	            	/*int ii=str1.substring(7).indexOf(':');
	              	Log.w(getClass().getName(), str1.substring(7)+"  ii "+ii);

	            	ser_port = Integer.parseInt(str1.substring(7+ii+1));
	            	Log.w(getClass().getName(), str1.substring(7,7+ii)+"   iii"+ser_port);
	            	//runTcpClient(str1.substring(7,7+ii),port_n);
	            	ser_url=str1.substring(7,7+ii);
	            	*/
	              	ser_url=str1.substring(7);
	      			SharedPreferences settings = getSharedPreferences("setting_infos", 0);  
	    			settings.edit().putString("URL", ser_url).commit();
	        	
	            	have_str=2;
	            	break;  
	            }
	            ii= str1.indexOf(";login");
	            if(ii>0)
	            {
	            	loginCMD=str1;
	            }
	            ii=str1.indexOf("uartInterface");//error
	            if(ii==0)
	            {
	            	update_loginID();
	            	start_activity();
	            	return;
	            }
	            have_str=1;
	            
	            ii= str1.indexOf("loaded");
	            if(ii==0)
	            {
	            	Log.w(getClass().getName(), "loaded:");
	            	have_str=4;
			BT_status=0;		
	            }
	            
	           
	            
	          //  mTimer.schedule(new MyTimerTask(), 1000,2 * 1000);  
	            break;  
//////////////////////////////////
	        case 1:  
	        	
	        	System.out.println( "mBluetoothAdapter receive: " +str1  );
	        	System.out.println( "mBluetoothAdapter  BT_status:"+BT_status );
	        	//ii=str1.indexOf("bluetooth");
	          //  if(ii==0)
	            {
	            	
	            
	            	
				if(BT_status==0)
	          		{
	          			ii= str1.indexOf("bluetooth scan");
	          			if(ii==0)
	          			{
		          			bluetooth_s.scanLeDevice(true);
		          			BT_status=1;
		          			System.out.println( "mBluetoothAdapter scan: " +str1 );
	          			}
	          		}

	          		 if(BT_status==1)
	          		{
	          		
					ii= str1.indexOf("bluetooth stop scan");
					if(ii==0)
					{
						bluetooth_s.scanLeDevice(false);
						BT_status=0;
						System.out.println( "mBluetoothAdapter stop scan: " +str1 );
						
					}
					ii= str1.indexOf("bluetooth connect");
	          			if(ii==0)
	          			{
	          				String num=str1.substring(17);
	          				System.out.println( "mBluetoothAdapter: connect "+num  );	
	          			//	bluetooth_s.connect_bt(Integer.parseInt(num));
	          				bluetooth_s.connect_bt(0);
	          				BT_status=2;
	          				System.out.println( "mBluetoothAdapter: connect ok "+num  );	
	          			}
	          		}
	          		else if(BT_status==2)
	          		{
	          			System.out.println( "mBluetoothAdapter: send "+str1  );
					ii= str1.indexOf("bluetooth disconnect");
	          			if(ii==0)
	          			{
	          				System.out.println( "mBluetoothAdapter: disconnect ");
						bluetooth_s.disconnect_bt();
						break;
	          			}
	          			byte[] charArray9 = str1.getBytes(Charset.forName("UTF-8"));
	          			bluetooth_s.writeChar1(charArray9);	
	          			System.out.println( "mBluetoothAdapter: send ok"  );	
	          		}
	            }
	          
	        break;
	        ////
	        case 2:  
	        	System.out.println( "hotwifi receive: " +str1 );

            	ii= str1.indexOf("open");
            	
				if(ii==0)
          		{
          			 
					 setWifiApEnabled(true);  
          			System.out.println( "hotwifi open: " +str1 );
          		}
	        break;
	            default:  
	                break;  
	            }  
	        
	        }         
		 
	};  
	//It's the messenger of server  
	private Messenger mMessenger = new Messenger(mHandler);
	private Object ctx;  
 
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
	     playlist=intent.getStringExtra(EXTRA_PLAYLIST);
	      useShuffle=intent.getBooleanExtra(EXTRA_SHUFFLE, false);
	       
         play(playlist, useShuffle);   
	     start_boardcast(this);
    Log.w(getClass().getName(), "mGot to play()!");
    
    return(START_REDELIVER_INTENT);
  }
  
  private void start_boardcast(Context context)
  {
	  return;
	/*
	  	if (isPlaying) 
	  		return;
	     isPlaying=true;
	  ////////////
	     Intent intent = new Intent(context, Alarmreceiver.class);  
	  //   intent.setAction("arui.alarm.action");  
	     PendingIntent sender = PendingIntent.getBroadcast(context, 0,  
	             intent, 0);  
	     long firstime = SystemClock.elapsedRealtime();  
	     AlarmManager am = (AlarmManager) context  
	             .getSystemService(Context.ALARM_SERVICE);  

	     // 10锟斤拷一锟斤拷锟斤拷锟节ｏ拷锟斤拷停锟侥凤拷锟酵广播  
	     am.setRepeating(AlarmManager.RTC_WAKEUP, firstime,  
	             20 * 1000, sender);    
	   //////////  	  
	  */
  }
  

  @Override
  public IBinder onBind(Intent intent) {
	  Log.w(getClass().getName(), "on bind!");
	  return mMessenger.getBinder();  
  //  return(null);
  }
  
 
	class MyTimerTask extends TimerTask {  
	    private int i;
	    
		@Override  
	    public void run() {  
	        if (i == 100) {  
	            i = 0;  
	        }  
	        try {  
	            //send the message to the client  
	      //  Message message = Message.obtain(null, CallService.TEST,i, 0); 
	       	Message msg = new Message();  
	        msg.what = CallService.TEST;
	       // Message msg = Message.obtain(null,  CallService.TEST);//MessengerService.TEST=0  
	    //    msg.replyTo = mMessenger;  
	        
	        Bundle bundle = new Bundle();    
	        bundle.putString("text1",str1);  //锟斤拷Bundle锟叫达拷锟斤拷锟斤拷锟�  
	        msg.setData(bundle);//mes锟斤拷锟斤拷Bundle锟斤拷锟斤拷锟斤拷锟斤拷 
	      
	        Log.w(getClass().getName(), "send message!");
	            cMessenger.send(msg);  
	        } catch (RemoteException e) {  
	                e.printStackTrace();  
	        }  
	            i++;  
	    }  
	}  
  @SuppressLint("NewApi")
private void play(String playlist, boolean useShuffle) {
    if (!isPlaying) {
		isPlaying=true;
		 System.out.println( "Notification:0 "  );
		Intent top_open=new Intent(this, MainActivity.class);
	    top_open.putExtra("DO", "top_open");
	    PendingIntent pendingIntent_open = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), top_open, 0);
	    
	//	PendingIntent pendingIntent_open = PendingIntent.getActivity(this,
		//	    0, top_open, PendingIntent.FLAG_UPDATE_CURRENT);
		////
	    Intent actionIntent = new Intent(this, CallService.class);
	    PendingIntent actionPendingIntent = PendingIntent.getService(this, 0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
	 //   builder.addAction(android.R.drawable.ic_media_pause, "PAUSE", actionPendingIntent);
	    
		Intent top_close=new Intent(this, MainActivity.class);
		top_close.putExtra("DO", "top_close");
		PendingIntent pendingIntent_close = PendingIntent.getActivity(this,
			    0, top_close, PendingIntent.FLAG_UPDATE_CURRENT);
		Bitmap largeIconBitmap = BitmapFactory.decodeResource(
			    getResources(), R.drawable.ic_launcher);
		
		Notification notification  = new Notification.Builder(this)
         .setContentTitle("Rsheep robot")
      //  .setContentText("Rsheep robot")
         .setPriority(Notification.PRIORITY_MAX) 
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentIntent(pendingIntent_open)
        .setAutoCancel(true)
        .addAction(android.R.drawable.presence_online, "run", pendingIntent_open)
        .addAction(android.R.drawable.presence_busy, "stop", pendingIntent_close)
        .build();
		/*
		Notification notification = new Notification.BigTextStyle(
			    new Notification.Builder(this)
			        .setContentTitle("Rsheep robot")
			        .setSmallIcon(R.drawable.ic_launcher)
			        .setLargeIcon(largeIconBitmap)
			        .addAction(R.drawable.ic_launcher, "open", pendingIntent_open)
			        .addAction(R.drawable.ic_launcher, "close", pendingIntent_close))
			    .bigText("BigText")
			    .setSummaryText("SummaryText")
			    .build();
			    */
	 
		// Notification notification = new Notification(R.drawable.ic_launcher,
		//	 getString(R.string.app_name), System.currentTimeMillis());

	//	 PendingIntent pendingintent = PendingIntent.getActivity(this, 0,
		// 	new Intent(this, MainActivity.class), 0);
		// notification.setLatestEventInfo(this, "Robot Sheep", "Rsheep is running",
		// 	pendingintent);
	//	 NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	////	 nm.notify(0, notification);
		// NotificationManager notificationManager = 
		//		  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
///
		//		notificationManager.notify(0, notification); 
		startForeground(0x111, notification);
	/**/
    }
    else
    {
   /* 	Intent dialogIntent = new Intent(this, MainActivity.class);
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(dialogIntent);
        Log.w(getClass().getName(), "Got to play)!");
        */
    }
  }
 
  public void start_activity()
  {

	 
	   
	  Intent intent = new Intent(getBaseContext(), MainActivity.class); 
	  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
	  startActivity(intent);
	   
	  
	 /* Intent dialogIntent = new Intent(this, MainActivity.class);
      dialogIntent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
      startActivity(dialogIntent);*/
	  Log.w(getClass().getName(), "start_activity");
  }
  
  @SuppressLint("NewApi")
private void stop() {
    if (isPlaying) 
    {
      Log.w(getClass().getName(), "Got to stop()!");
      isPlaying=false;
      stopForeground(true);
    }
  }
  
  private void runTcpClient(String service_url,int service_port) {
	  try {
         // Csocket = new Socket("sluojin.herokuapp.com",80);
		  Log.w(getClass().getName(),service_url+"port:"+service_port);
         // Csocket = new Socket("192.168.0.5", 9002);
		  Csocket = new Socket(service_url, service_port);
          Cin = new BufferedReader(new InputStreamReader(Csocket.getInputStream()));
          Cout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(Csocket.getOutputStream())), true);
      } catch (IOException ex) {
          ex.printStackTrace();
          
      }
	} 
//handler锟斤拷锟斤拷锟斤拷锟斤拷锟�  
  Handler handler = new Handler() {  
      public void handleMessage(Message msg) {  
          if (msg.what == 1) {  
        	 
            //  System.out.println("receive1111....");  
          }  
      };  
  };



public void SendMessage_toMain(String sendstr)
{
	try {  
        //send the message to the client  
  //  Message message = Message.obtain(null, CallService.TEST,i, 0); 
   	Message msg = new Message();  
    msg.what = CallService.TEST;
   // Message msg = Message.obtain(null,  CallService.TEST);//MessengerService.TEST=0  
//    msg.replyTo = mMessenger;  
    
    Bundle bundle = new Bundle();    
    bundle.putString("text1",sendstr);  //锟斤拷Bundle锟叫达拷锟斤拷锟斤拷锟�  
  /*  int   ii=sendstr.indexOf(";onPause");
    if(ii>=0)
    {
    	onpause=1;
	return;
    }*/
    msg.setData(bundle);//mes锟斤拷锟斤拷Bundle锟斤拷锟斤拷锟斤拷锟斤拷 
  
    Log.w(getClass().getName(), "send message!"+sendstr);
        cMessenger.send(msg);  
    } catch (RemoteException e) {  
            e.printStackTrace();  
    }  	

}

  /** This example demonstrates how to create a websocket connection to a server. Only the most important callbacks are overloaded. */
  public class ExampleClient extends WebSocketClient {

      public ExampleClient( URI serverUri , Draft draft ) {
              super( serverUri, draft );
      }

      public ExampleClient( URI serverURI ) {
              super( serverURI );
      }
	  


      @Override
      public void onOpen( ServerHandshake handshakedata ) {
              System.out.println( "opened connection" );
              // if you plan to refuse connection based on ip or httpfields overload: onWebsocketHandshakeReceivedAsClient
      }

      @Override
      public void onMessage( String message ) {
    	  	  int ii=0;
              
              
              System.out.println(" received: " + message );
              
              onLine_n=0;
              ii=message.indexOf(";call;");
              if(ii>0)
              {
	            	 if((isForeground("org.crosswalkproject.xwalkembed")==false)
	            			 ||(ScreenReceiver.wasScreenOn==false))
	            	  {
		            	  start_activity();
				  onpause=0;
		            	   
		          }
	            	  else
	            		  have_str=4;
	            	  wait_load=1;
	            	  ii=message.indexOf(";");           	 
	            	  answser1=message.substring(ii+6)+";answer;"+message.substring(0,ii);
	            	  System.out.println( "answer1: " + answser1 );
              }
              ii=message.indexOf(";hang up;");
              if(ii>0)
              {
            	  bluetooth_s.disconnect_bt();
	            	 if((isForeground("org.crosswalkproject.xwalkembed")==true)
	            			 &&(ScreenReceiver.wasScreenOn==true))
	            	  {
	            		 
		            	  start_activity();
				  onpause=0;
		            	   
		          }
	            	  else
	            		  have_str=4;
	            	  wait_load=1;
	            	  ii=message.indexOf(";");           	 
	            	  answser1=message.substring(ii+9)+";hang up ok;"+message.substring(0,ii);
	            	  System.out.println( "answer hang up: " + answser1 );
              }

			  
              ii=message.indexOf("hi sheep");
              if(ii==0)
              {
            	  ii=loginCMD.indexOf(";login");
            	  c.send(loginCMD.substring(0, ii)+";live"); 
            	//  System.out.println(" received11122: " + message );
              }
              SendMessage_toMain(message);
      }

      @Override
      public void onFragment( Framedata fragment ) {
              System.out.println( "received fragment: " + new String( fragment.getPayloadData().array() ) );
      }

      @Override
      public void onClose( int code, String reason, boolean remote ) {
              // The codecodes are documented in class org.java_websocket.framing.CloseFrame
              System.out.println( "Connection closed by " + ( remote ? "remote peer" : "us reason:" )  +reason);
              have_str=3;
      }

      @Override
      public void onError( Exception ex ) {
              ex.printStackTrace();
              System.out.println( "Connection onError"  );
            //  have_str=3;
                       
              // if the error is fatal then onClose will be called additionally
      }
  }
  
  private void start_websocket()
  {
	  
	 if(ser_url.length()<2)
		 return;
	try {
	//	c = new ExampleClient( new URI( "ws://sluojin.herokuapp.com:80" ), new Draft_17() );
		c = new ExampleClient( new URI( "ws://"+ser_url ), new Draft_17() );
	} catch (URISyntaxException e) {
		// TODO Auto-generated catch block
		//have_str=3;
		e.printStackTrace();
	} 
      try {
		c.connectBlocking();
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
	//	have_str=3;
		e.printStackTrace();
	}
      try {
		Thread.sleep(500);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		//have_str=3;
		e.printStackTrace();
	}
    if(loginCMD!=null)
    {
    	if (!c.isClosed()) 
    	{
    		c.send(loginCMD);
    		have_str=0;
    	}
    	
    	
    }
     // c.send("handshake");
	
  }


  public boolean isForeground(String myPackage) {
	  ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
	  List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1); 
	  ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
	  System.out.println( "pakagename: " + componentInfo.getPackageName() );
	  return componentInfo.getPackageName().equals(myPackage);
  }


  // 锟竭筹拷锟斤拷  
  class ThreadShow extends Thread {  

      private int cn;

	@Override  
      public void run() {  
          // TODO Auto-generated method stub  
        	//uartInterfaceC.SetConfig(9600, (byte)8, (byte)1, (byte)0, (byte)0);	

    	  Log.w(getClass().getName(), "send22222");
           while (true) {  
            
        	  if(have_str==2)
        	  {
        		  if(c==null)
        			  start_websocket();
        		  if (c.isClosed())
        			  start_websocket();
        		  have_str=0;
        	  }
        	  if(have_str==3)
        		  start_websocket();
        	  if(c!=null)
        	  {
            	  if (c.isClosed()) 
            	  {
            		  start_websocket();
            		  
            	  }
        	  } 
        	  if((have_str==1)&&(c!=null))
        	  {
        		  if (!c.isClosed()) 
                  {
        			  Log.w(getClass().getName(), "send22222:"+str1);
        			  c.send(str1);
        			  cn++;
        			//  if((cn%2)==1)
        			//	  uartInterfaceC.SendData("b4000;\r\n".length(), "b4000;\r\n".getBytes());
        			//  else
        			//	  uartInterfaceC.SendData("b0;\r\n".length(), "b0;\r\n".getBytes());
                  }
        		 
        		  have_str=0;
        	  }
        	  if(wait_load==1&&have_str==4&&(c!=null))
        	  {
        		  if (!c.isClosed()&&(answser1.length()>0)) 
        		  {
        			  Log.w(getClass().getName(), "send answser1:");
        			  c.send(answser1);
        		  }
        		  wait_load=0;
        		  have_str=0;
        	  }
        	  onLine_n++;	  
              if(onLine_n>800)	  
              {
            	  onLine_n=0;
            	  have_str=3;
            	  Log.w(getClass().getName(), "reconnect111:");
              }
              try {
				Thread.sleep(50);
              } catch (InterruptedException e) {
				// TODO Auto-generated catch block
            	  Log.w(getClass().getName(), "thread error!");
				e.printStackTrace();
              }  
            //  Message msg = new Message();  
                //  msg.what = 1;  
                 // handler.sendMessage(msg);  
               //   play(playlist, useShuffle);
                // Log.w(getClass().getName(), "send11111!");
                 
              
          }  
      }  
  }
public void BT_callback(String sendstr) {
	// TODO Auto-generated method stub
	SendMessage_toMain(sendstr);
	System.out.println( "mBluetoothAdapter callback: " +sendstr );
	
}  
  
 
}
